package com.itsu.compoment.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.itsu.compoment.socket.MyWebSocketHandler;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.web.socket.TextMessage;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Set;

/**
 * @author 苏犇
 * @create time 2019/12/8 16:50
 */
@Slf4j
public class BootMsgConfirmListener implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        log.info("收到消息：{}", JSON.toJSONString(message));
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
//        if (true) {
//            return;
//        }
        byte[] bytes = message.getBody();
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        com.itsu.compoment.socket.Message msg = (com.itsu.compoment.socket.Message) ois.readObject();
        Set<String> loginUsers = MyWebSocketHandler.getLoginUsers();
        if (loginUsers.contains(msg.getToUserId())) {
            TextMessage tms = new TextMessage(JSON.toJSONStringWithDateFormat(msg,"yyyy-MM-dd hh:mm:ss"));
            MyWebSocketHandler.sendMessageToUser(msg.getToUserId(),tms);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("用户已上线，确认签收消息");
        } else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            log.info("用户尚未上线，退还消息至rabbitmq");
        }

    }
}
